package com.bxd.baodan.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lizhichao on 18/1/13.
 */

public class GsonUtil<T> {
    private static Gson gson = new Gson();

    private GsonUtil() {
        gson = new Gson();
    }

//    private static class GsonUtilHolder {
//        private static final GsonUtil instance = new GsonUtil();
//    }
//
//    public static GsonUtil getInstance() {
//        return GsonUtilHolder.instance;
//    }

    public static<T>   T fromJson(String str, Class clazz) {

        return (T) gson.fromJson(str, clazz);
    }



    public static String toJson(Object object) {

      return   gson.toJson(object);
    }

    public static <T> List<T> fromJsonList(String str, Class<T> clazz) {
        List<T> lst = new ArrayList<>();
        try {
            JsonArray array = new JsonParser().parse(str).getAsJsonArray();
            for (final JsonElement elem : array) {
                lst.add(gson.fromJson(elem, clazz));
            }
        } catch (Exception e) {
        }
        return lst;
    }
}
